[[...path]].page.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import React, { useEffect } from 'react';
  2. import { type IPagePopulatedToShowRevision, getIdForRef } from '@growi/core';
  3. import type {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  11. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  12. import { ShareLinkPageView } from '~/components/ShareLinkPageView';
  13. import type { SupportedActionType } from '~/interfaces/activity';
  14. import { SupportedAction } from '~/interfaces/activity';
  15. import type { CrowiRequest } from '~/interfaces/crowi-request';
  16. import { RegistrationMode } from '~/interfaces/registration-mode';
  17. import type { RendererConfig } from '~/interfaces/services/renderer';
  18. import type { IShareLinkHasId } from '~/interfaces/share-link';
  19. import type { PageDocument, PageModel } from '~/server/models/page';
  20. import ShareLink from '~/server/models/share-link';
  21. import {
  22. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  23. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid, useIsEnabledMarp,
  24. useIsLocalAccountRegistrationEnabled, useShowPageSideAuthors,
  25. } from '~/stores-universal/context';
  26. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  27. import loggerFactory from '~/utils/logger';
  28. import type { NextPageWithLayout } from '../_app.page';
  29. import type { CommonProps } from '../utils/commons';
  30. import {
  31. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, skipSSR, addActivity,
  32. } from '../utils/commons';
  33. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  34. const logger = loggerFactory('growi:next-page:share');
  35. type Props = CommonProps & {
  36. shareLinkRelatedPage?: IShareLinkRelatedPage,
  37. shareLink?: IShareLinkHasId,
  38. isNotFound: boolean,
  39. isExpired: boolean,
  40. disableLinkSharing: boolean,
  41. isSearchServiceConfigured: boolean,
  42. isSearchServiceReachable: boolean,
  43. isSearchScopeChildrenAsDefault: boolean,
  44. showPageSideAuthors: boolean,
  45. isEnabledMarp: boolean,
  46. isLocalAccountRegistrationEnabled: boolean,
  47. drawioUri: string | null,
  48. rendererConfig: RendererConfig,
  49. skipSSR: boolean,
  50. ssrMaxRevisionBodyLength: number,
  51. };
  52. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  53. superjson.registerCustom<IShareLinkRelatedPage, string>(
  54. {
  55. isApplicable: (v): v is IShareLinkRelatedPage => {
  56. return v != null
  57. && v.toObject != null;
  58. },
  59. serialize: (v) => { return superjson.stringify(v.toObject()) },
  60. deserialize: (v) => { return superjson.parse(v) },
  61. },
  62. 'IShareLinkRelatedPageTransformer',
  63. );
  64. // GrowiContextualSubNavigation for shared page
  65. // get page info from props not to send request 'GET /page' from client
  66. type GrowiContextualSubNavigationForSharedPageProps = {
  67. page?: IPagePopulatedToShowRevision,
  68. isLinkSharingDisabled: boolean,
  69. }
  70. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  71. const { page, isLinkSharingDisabled } = props;
  72. return (
  73. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled} />
  74. );
  75. };
  76. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  77. useCurrentPathname(props.shareLink?.relatedPage.path);
  78. useIsSearchPage(false);
  79. useIsNotFound(props.isNotFound);
  80. useShareLinkId(props.shareLink?._id);
  81. useCurrentPageId(props.shareLink?.relatedPage._id);
  82. useCurrentUser(props.currentUser);
  83. useRendererConfig(props.rendererConfig);
  84. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  85. useIsSearchServiceReachable(props.isSearchServiceReachable);
  86. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  87. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  88. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  89. useShowPageSideAuthors(props.showPageSideAuthors);
  90. useIsContainerFluid(props.isContainerFluid);
  91. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  92. useEffect(() => {
  93. if (!props.skipSSR) {
  94. return;
  95. }
  96. if (props.shareLink?.relatedPage._id != null && !props.isNotFound) {
  97. mutateCurrentPage();
  98. }
  99. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  100. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  101. const title = generateCustomTitleForPage(props, pagePath);
  102. return (
  103. <>
  104. <Head>
  105. <title>{title}</title>
  106. </Head>
  107. <div className="dynamic-layout-root justify-content-between">
  108. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  109. <ShareLinkPageView
  110. pagePath={pagePath}
  111. rendererConfig={props.rendererConfig}
  112. page={currentPage ?? props.shareLinkRelatedPage}
  113. shareLink={props.shareLink}
  114. isExpired={props.isExpired}
  115. disableLinkSharing={props.disableLinkSharing}
  116. />
  117. </div>
  118. </>
  119. );
  120. };
  121. SharedPage.getLayout = function getLayout(page) {
  122. return (
  123. <>
  124. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  125. <ShareLinkLayout>{page}</ShareLinkLayout>
  126. </>
  127. );
  128. };
  129. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  130. const req: CrowiRequest = context.req as CrowiRequest;
  131. const { crowi } = req;
  132. const { configManager, searchService } = crowi;
  133. props.disableLinkSharing = configManager.getConfig('security:disableLinkSharing');
  134. props.isSearchServiceConfigured = searchService.isConfigured;
  135. props.isSearchServiceReachable = searchService.isReachable;
  136. props.isSearchScopeChildrenAsDefault = configManager.getConfig('customize:isSearchScopeChildrenAsDefault');
  137. props.drawioUri = configManager.getConfig('app:drawioUri');
  138. props.showPageSideAuthors = configManager.getConfig('customize:showPageSideAuthors');
  139. props.isLocalAccountRegistrationEnabled = crowi.passportService.isLocalStrategySetup
  140. && configManager.getConfig('security:registrationMode') !== RegistrationMode.CLOSED;
  141. props.rendererConfig = {
  142. isSharedPage: true,
  143. isEnabledLinebreaks: configManager.getConfig('markdown:isEnabledLinebreaks'),
  144. isEnabledLinebreaksInComments: configManager.getConfig('markdown:isEnabledLinebreaksInComments'),
  145. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  146. adminPreferredIndentSize: configManager.getConfig('markdown:adminPreferredIndentSize'),
  147. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  148. drawioUri: configManager.getConfig('app:drawioUri'),
  149. plantumlUri: configManager.getConfig('app:plantumlUri'),
  150. // XSS Options
  151. isEnabledXssPrevention: configManager.getConfig('markdown:rehypeSanitize:isEnabledPrevention'),
  152. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  153. customTagWhitelist: crowi.configManager.getConfig('markdown:rehypeSanitize:tagNames'),
  154. customAttrWhitelist: configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  155. ? JSON.parse(configManager.getConfig('markdown:rehypeSanitize:attributes'))
  156. : undefined,
  157. highlightJsStyleBorder: crowi.configManager.getConfig('customize:highlightJsStyleBorder'),
  158. };
  159. props.ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  160. }
  161. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  162. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  163. props._nextI18Next = nextI18NextConfig._nextI18Next;
  164. }
  165. function getAction(props: Props): SupportedActionType {
  166. let action: SupportedActionType;
  167. if (props.isExpired) {
  168. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  169. }
  170. else if (props.shareLink == null) {
  171. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  172. }
  173. else {
  174. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  175. }
  176. return action;
  177. }
  178. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  179. const req = context.req as CrowiRequest;
  180. const { crowi, params } = req;
  181. const result = await getServerSideCommonProps(context);
  182. if (!('props' in result)) {
  183. throw new Error('invalid getSSP result');
  184. }
  185. const props: Props = result.props as Props;
  186. try {
  187. const shareLink = await ShareLink.findOne({ _id: params.linkId }).populate('relatedPage');
  188. if (shareLink == null) {
  189. props.isNotFound = true;
  190. }
  191. else {
  192. props.isNotFound = false;
  193. props.isExpired = shareLink.isExpired();
  194. props.shareLink = shareLink.toObject();
  195. // retrieve Page
  196. const Page = crowi.model('Page') as PageModel;
  197. const relatedPage = await Page.findOne({ _id: getIdForRef(shareLink.relatedPage) });
  198. // determine whether skip SSR
  199. const ssrMaxRevisionBodyLength = crowi.configManager.getConfig('app:ssrMaxRevisionBodyLength');
  200. if (relatedPage != null) {
  201. props.skipSSR = await skipSSR(relatedPage, ssrMaxRevisionBodyLength);
  202. // populate
  203. props.shareLinkRelatedPage = await relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  204. }
  205. }
  206. }
  207. catch (err) {
  208. logger.error(err);
  209. }
  210. injectServerConfigurations(context, props);
  211. await injectNextI18NextConfigurations(context, props);
  212. await addActivity(context, getAction(props));
  213. return {
  214. props,
  215. };
  216. };
  217. export default SharedPage;